package com.yymx.toback.api.controller.sms;


import com.yymx.toback.common.base.BaseApiController;
import com.yymx.toback.common.base.BaseResult;
import com.yymx.toback.common.constants.RedisConstants;
import com.yymx.toback.common.enums.ResultEnum;
import com.yymx.toback.common.enums.SmsStatusEnum;
import com.yymx.toback.common.enums.YunpianSmsTemplateEnum;
import com.yymx.toback.common.exception.ParamException;
import com.yymx.toback.common.redis.RedisUtil;
import com.yymx.toback.common.sms.YunPianSmsSdk;
import com.yymx.toback.common.util.MyIpUtils;
import com.yymx.toback.common.util.RegexUtils;
import com.yymx.toback.dto.sms.vo.UserSmsVo;
import com.yymx.toback.service.sms.IUserSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: zcg
 * @Date: 2019/3/25 15:38
 * @Description:短信验证码接口类
 */
@RestController
@RequestMapping("/sms/")
@Slf4j
public class SmsController extends BaseApiController {


    @Autowired
    private IUserSmsService userSmsService;


    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("sendSMSCode")
    public BaseResult sendSmsCode(@RequestBody UserSmsVo userSmsVo, HttpServletRequest request){

        try {
            checkMobile(userSmsVo.getPhone());
            String indentifyCode = YunPianSmsSdk.createIndentifyCode(6);

            userSmsVo.setContent(YunpianSmsTemplateEnum.getType(userSmsVo.getType()).getDescription().replace("#code#",indentifyCode));
            userSmsVo.setType(userSmsVo.getType());
            userSmsVo.setPhone(userSmsVo.getPhone());
            userSmsVo.setRequestIp(MyIpUtils.getClientIpAddress(request));
            BaseResult result = userSmsService.send(userSmsVo);
            //把发送的短信验证码存入到redis
            redisUtil.set(RedisConstants.REDIS_SMS_CODE +userSmsVo.getPhone(),indentifyCode, RedisConstants.REDIS_SMS_CODE_EXPIRED);
            return result;
        } catch (Exception e) {
            log.error("短信发送异常 {} ",e.getMessage());
        }
        return BaseResult.failMsg (SmsStatusEnum.SEND_FAIL.getMessage());
    }

    private void checkMobile(String phone){
        if(!RegexUtils.isMobile(phone)){
            throw  new ParamException(ResultEnum.USER_PHONE_IS_WRONG.getMsg());
        }
    }


    @RequestMapping("/verifySms")
    public BaseResult verifySms(@RequestBody UserSmsVo userSmsVo){
        try {
        	return userSmsService.checkSms(userSmsVo);
        } catch (Exception e) {
            return BaseResult.failCodeMsg(ResultEnum.ERROR.getCode(),ResultEnum.ERROR.getMsg()+":"+e.getMessage());
        }
    }






}
